//
//  XZSearchResultVC.m
//  Teecloud
//
//  Created by PC on 2018/11/2.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZSearchResultVC.h"
#import <SafariServices/SafariServices.h>
#import "XZNewsCaseVC.h"

#import "XZSearchBar.h"
#import "GMHomeImgCell.h"
#import "GMNewsViewCell.h"

#import "XZNewsList.h"
@interface XZSearchResultVC ()<UITableViewDataSource,UITableViewDelegate,SFSafariViewControllerDelegate,UISearchBarDelegate>
@property (nonatomic, copy) NSString *searchKey;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) XZSearchBar *searchBar;
@property (nonatomic, strong) UITableView *tableView;
@end
#define NEWSLISTCELL @"XZNewsHeadView"
#define NEWSBANNERCELL @"GMHomeImgCell"
@implementation XZSearchResultVC
- (void)dealloc{
    XZLog(@"%s",__FUNCTION__);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kWhiteColor;
    [self creatTitleView];
    self.searchKey = self.key;
    [self pullNewsData];
    //监听当键将要退出时
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

//当键退出
- (void)keyboardWillHide:(NSNotification *)notification{
    if ([self.searchBar.text isEqualToString:@""]) {//为空的时候就用传过来的key搜索
        self.searchKey = self.key;
    }else{
        self.searchKey = self.searchBar.text;
    }
    [self pullNewsData];
}
//搜索框
- (void)creatTitleView{
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, 44)];
    titleView.backgroundColor = [UIColor clearColor];
    //设置titleview，不过这个view并不是我们需要的居中的view；
    self.navigationItem.titleView = titleView;
    __weak typeof(self) weakSelf = self;
    //主线程列队一个block， 这样做 可以获取到autolayout布局后的frame，也就是titleview的frame。在viewDidLayoutSubviews中同样可以获取到布局后的坐标
    __block XZSearchBar *searchBar;
    dispatch_async(dispatch_get_main_queue(), ^{
        //要居中view的宽度
        CGFloat width = 240;
        //实际居中的view
        UIView *centerView = [[UIView alloc]init];
        centerView.backgroundColor = kClearColor;
        //设置一个基于window居中的坐标
        centerView.frame = CGRectMake((DEVICE_WIDTH-width)/2, 20+(kIs_iPhoneX?24:0), width, 44);
        //坐标系转换到titleview
        centerView.frame = [weakSelf.view.window convertRect:centerView.frame toView:weakSelf.navigationItem.titleView];
        searchBar = [[XZSearchBar alloc]initWithFrame:CGRectMake(0, 10, 240, 30)];
        searchBar.delegate = self;
        searchBar.placeholder = @"输入关键字";
        searchBar.text = self.key;
        searchBar.tintColor = kBlueColor;
        [centerView addSubview:searchBar];
        self.searchBar = searchBar;
        //centerview添加到titleview
        [weakSelf.navigationItem.titleView addSubview:centerView];
    });
}
#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
}
#pragma mark - Networking
/*
 *更新广告阅读计数
 */
-(void)updateReadCount:(NSString *)addId{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    //广告Id
    [dict setValue:addId forKey:@"adId"];
    
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"/ajax-api.ashx?$c=TeeyunApp&$m=UpdateAdCount&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                XZLog(@"计数成功");
            }else{
                XZLog(@"计数失败");
            }
            
        }else{
            XZLog(@"%@",error);
        }
    }];
}
#pragma mark -MJRefresh
- (void)pullNewsData{
    self.pageIndex = 0;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    [dict setValue:self.searchKey forKey:@"key"];
    __weak typeof(self)weakSelf = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetNewsList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *dataInfo = [responseObject objectForKey:RESULT_NAME_Data];
                NSArray *newsArray = [XZNewsList mj_objectArrayWithKeyValuesArray:dataInfo];
                [weakSelf.dataSource removeAllObjects];
                [weakSelf.dataSource addObjectsFromArray:newsArray];
                [weakSelf.tableView.mj_footer endRefreshing];
                [weakSelf.tableView.mj_header endRefreshing];
                if (weakSelf.dataSource.count == 0) {
                    [weakSelf.tableView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakSelf.tableView reloadData];
            }else{
                
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakSelf.view];
            }
            
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakSelf.view];
        }
    }];
}
- (void)addMoreNewsData{
    self.pageIndex ++;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    [dict setValue:self.searchKey forKey:@"key"];
    __weak typeof(self)weakSelf = self;
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetNewsList&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *dataInfo = [responseObject objectForKey:RESULT_NAME_Data];
                NSArray *newsArray = [XZNewsList mj_objectArrayWithKeyValuesArray:dataInfo];
                [weakSelf.dataSource addObjectsFromArray:newsArray];
                if (dataInfo.count>0) {
                    [weakSelf.tableView.mj_footer endRefreshing];
                    [weakSelf.tableView.mj_header endRefreshing];
                    [weakSelf.tableView reloadData];
                }else{//没有数据的时候就显示暂无数据
                    weakSelf.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                }
            }else{
                [weakSelf.tableView.mj_footer endRefreshing];
                [weakSelf.tableView.mj_header endRefreshing];
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakSelf.view];
            }
        }else{
            [weakSelf.tableView.mj_footer endRefreshing];
            [weakSelf.tableView.mj_header endRefreshing];
             [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakSelf.view];
        }
    }];
}
#pragma mark - TableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    self.tableView.mj_footer.hidden = self.dataSource.count > 0? NO:YES;
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    XZNewsList *model = self.dataSource[indexPath.row];
    UITableViewCell *cell = nil;
    if (!model.IsAd) {
        GMNewsViewCell *newsViewCell = [tableView dequeueReusableCellWithIdentifier:NEWSLISTCELL forIndexPath:indexPath];
        newsViewCell.model = model;
        cell = newsViewCell;
    }else{
        GMHomeImgCell *homeImageCell = [tableView dequeueReusableCellWithIdentifier:NEWSBANNERCELL];
        homeImageCell.newsModel = model;
        cell = homeImageCell;
    }
    return cell;
}
#pragma mark - TableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    XZNewsList *model = self.dataSource[indexPath.row];
    if (!model.IsAd) {
        return 100;
    }else{
        return 80;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    XZNewsList *model = self.dataSource[indexPath.row];
    if (model.IsAd) {//广告 就更新阅读计数
        [self updateReadCount:model.Id];
    }
    [self skipControllerWithNewsListModel:model];
}
/************************点击cell进行跳转**********************/
/*
 **根据相应的参数值进行跳转
 */
- (void)skipControllerWithNewsListModel:(XZNewsList *)model{
    if (1 == [model.RelType integerValue]) {//model.RelType=1
        [self relTypeIsEqualOneSkipControllerWithNewsListModel:model];
    }else if (2 == [model.RelType integerValue]){//model.RelType=2
        [self skipOrganizationOrGroupWithNewsListModel:model];
    }else if (3 == [model.RelType integerValue]){//新闻资讯案例
        XZNewsCaseVC *newsCaseVC = [[XZNewsCaseVC alloc]init];
        newsCaseVC.newsId = model.Id;
        [self.navigationController pushViewController:newsCaseVC animated:true];
    }else if (4 == [model.RelType integerValue]){//广告详情页面基地址
        NSString *adUrlString = [NSString stringWithFormat:@"%@/%@",URL_ADURL,model.Id];
        SFSafariViewController *sfVC = [[SFSafariViewController alloc]initWithURL:[NSURL URLWithString:adUrlString]];
        sfVC.delegate = self;
        [self presentViewController:sfVC animated:YES completion:nil];
    }
}
/*
 **如model.RelType=1
 *进行相应的跳转
 */
- (void)relTypeIsEqualOneSkipControllerWithNewsListModel:(XZNewsList *)model{
    if (0 == [model.NormalCode integerValue]) {
        [self skipNormalCodeIsZeroControllerWithNewsListModel:model];
    }else if (1 == [model.NormalCode integerValue]){
        [MBProgressHUD showErrorOrSuc:@"资源不可用" toView:self.view];
    }else if (2 == [model.NormalCode integerValue]){
        [MBProgressHUD showErrorOrSuc:@"非购买资源手机" toView:self.view];
    }
}
/*
 *当model.NormalCode=0时 根据ResType及IsAdded进行相应的跳转
 */
- (void)skipNormalCodeIsZeroControllerWithNewsListModel:(XZNewsList *)model{
    if (1 == [model.ResType integerValue]) {//视频
        if (!model.IsFree) {
            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 试看(视频)“页面" toView:self.view];
        }else{
            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 播放 - 问题“页面" toView:self.view];
        }
    }else if (2 == [model.ResType integerValue]){//文档
        if (!model.IsFree) {
            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 详情(文档)“页面" toView:self.view];
        }else{
            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 文档“页面" toView:self.view];
        }
    }else if (3 == [model.ResType integerValue]){//习题
        if (!model.IsFree) {
            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 详情(习题、试卷)“页面" toView:self.view];
        }else{
            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 习题 - 答题“页面" toView:self.view];
        }
    }else if (4 == [model.ResType integerValue]){//试卷
        if (!model.IsFree) {
            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 详情(习题、试卷)“页面" toView:self.view];
        }else{
            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 试卷考试 - 考试须知“页面" toView:self.view];
        }
    }else if (9 == [model.ResType integerValue]){//课程包
        if (!model.IsFree) {
            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 资源 - 学习资源 - 详情(课程包)“页面" toView:self.view];
        }else{
            [MBProgressHUD showErrorOrSuc:@"跳转”主页 - 我的 - 我的资源 - 课程包“页面" toView:self.view];
        }
    }
}
/*
 **如model.RelType=2
 * true=IsAdded：跳转”主页 - 我的 - 我的社团/小组 - 详情“页面
 * false=IsAdded：跳转”主页 - 资源 - 社团/小组 - 介绍“页面
 */
- (void)skipOrganizationOrGroupWithNewsListModel:(XZNewsList *)model{
    if (!model.IsAdded) {
        [MBProgressHUD showErrorOrSuc:@"社团/小组 - 介绍页面" toView:self.view];
    }else{
        [MBProgressHUD showErrorOrSuc:@" 我的社团/小组 详情界面" toView:self.view];
    }
    
}
#pragma mark - SFSafariViewControllerDelegate -
- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller{
    XZLog(@"击done");
}
#pragma mark - Setter
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource =[[NSMutableArray alloc]init];
    }
    return _dataSource;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT-kNavBarAndStatusBarHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([GMNewsViewCell class]) bundle:nil] forCellReuseIdentifier:NEWSLISTCELL];
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([GMHomeImgCell class]) bundle:nil] forCellReuseIdentifier:NEWSBANNERCELL];
        //上下拉刷新
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(pullNewsData)];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(addMoreNewsData)];
        _tableView.mj_footer.hidden =YES;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}




@end
